import base64
import json
from Crypto.Cipher import AES

# 1. 从Java代码中找到的硬编码Base64密钥
BASE64_ENCODED_KEY = "isvrbeT7qUywVEZ1Ia0/aUVA/TcFaeV0wC8qFLc8rg4="

# 2. 将其解码一次，得到AES加密所需的原始key字节
#    这个操作在程序生命周期中只需要执行一次
KEY_BYTES = base64.b64decode(BASE64_ENCODED_KEY)


def decode_final_captcha_data(raw_base64_string: str):
    """
    根据Java源码逆向出的最终解密函数。
    流程: Base64 -> (文本 -> 分割) -> (Base64 -> 密文) + (Base64 -> IV) -> AES解密 -> JSON
    """
    print("日志: 开始最终解密流程...")
    
    try:
        # 步骤1: 第一次Base64解码
        decoded_string_with_separator = base64.b64decode(raw_base64_string).decode('utf-8')
        print("日志: 第一次Base64解码成功。")

        # 步骤2: 使用 '%IV1%' 分割字符串
        parts = decoded_string_with_separator.split('%IV1%')
        if len(parts) != 2:
            raise ValueError("分割后的数据部分不等于2，格式不正确。")
        
        encrypted_data_b64 = parts[0]
        iv_data_b64 = parts[1]
        print("日志: 密文和IV分割成功。")

        # 步骤3: 第二次和第三次Base64解码，分别获取密文和IV
        ciphertext = base64.b64decode(encrypted_data_b64)
        iv_bytes = base64.b64decode(iv_data_b64)
        print("日志: 密文和IV的Base64解码成功。")

        # 步骤4: 创建AES-CTR cipher并解密
        # 注意：CTR模式不需要padding，也不需要unpad函数
        cipher = AES.new(KEY_BYTES, AES.MODE_CTR, nonce=iv_bytes)
        decrypted_bytes = cipher.decrypt(ciphertext)
        print("日志: AES-CTR解密成功。")

        # 步骤5: UTF-8解码并解析JSON
        json_string = decrypted_bytes.decode('utf-8')
        final_data = json.loads(json_string)
        print("日志: JSON解析成功！")
        
        return final_data

    except Exception as e:
        print(f"错误: 处理过程中出现异常。错误信息: {e}")
        return None

# --- 主程序入口 ---
if __name__ == "__main__":
    # 请将这里替换为您从服务器获取的那个最原始的Base64字符串
    new_b64_str = "rAAUAOWupsLOocedhME1BQtQaeN5tzthaRnucX+WKP97zTbG1ruwLFbu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证码数据 " + "="*20)
    captcha_info = decode_final_captcha_data(new_b64_str)
    
    if captcha_info:
        print("\n" + "="*20 + "  最终解析结果  " + "="*20)
        pretty_result = json.dumps(captcha_info, indent=2, ensure_ascii=False)
        print(pretty_result)
        print("="*58)
